#ifndef NETWORKSERVICES_CONNECTION_H
#define NETWORKSERVICES_CONNECTION_H

#include <atomic>
#include <memory>
#include <functional>
#include <ctime>
#include "../common/Buffer.h"
#include "../common/HSocket.h"

class Channel;
class EventLoop;
class Connection;

typedef std::shared_ptr<Connection> ConnectionPtr;

class Connection : public std::enable_shared_from_this<Connection> {
public:
    Connection(EventLoop *loop, Socket clientSock);
    ~Connection();
    int GetFd() const;
    std::string GetIp() const;
    uint16_t GetPort() const;
    void OnMessage();
    void Close();
    void Error();
    void Write();
    void Send(const char *data, size_t size);
    void SendInLoop(const std::shared_ptr<std::string> &data);
    bool Timeout(time_t now, int val) const;

public:
    std::function<void(ConnectionPtr)> onClose;
    std::function<void(ConnectionPtr)> onError;
    std::function<void(ConnectionPtr, std::string &)> onMessage;
    std::function<void(ConnectionPtr)> onSendComplete;
    time_t lastTime{};

private:
    EventLoop *loop;
    Socket clientSock;
    std::unique_ptr<Channel> clientChannel;
    Buffer inputBuffer;
    Buffer outputBuffer;
    std::atomic<bool> disconnect = true;
};


#endif //NETWORKSERVICES_CONNECTION_H
